//
//  homeViewController.m
//  IMGII
//
//  Created by 步遴 李 on 12-4-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "homeViewController.h"
#import "AppDelegate.h"
#import "RegexKitLite.h"
#import "AFNetworking.h"

@implementation homeViewController
@synthesize blog,controllers,topBar,blogstable,blogs,butNew,butInfo,butProduct,butSkill,butPs,butEquip,pre,operationQueue;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [self.blog release];
    [self.operationQueue release];
    [super dealloc];
}
#pragma mark - View lifecycle

-(IBAction)ButClick:(id)sender
{   
    if (_reloading) 
        return;
    
    UIBarItem *bt = (UIBarItem*)sender;
    switch (bt.tag) {
        case 0:
            self.pre = nil;
            break;
        case 1:
            self.pre = [NSPredicate predicateWithFormat:
                   @"(category like %@)",@"*业界资讯*"];
            break;
        case 2:
            self.pre = [NSPredicate predicateWithFormat:
                   @"(category like %@)",@"*摄影欣赏*"];
            break;
        case 3:
            self.pre = [NSPredicate predicateWithFormat:
                   @"(category like %@)",@"*摄影技巧*"];
            break;
        case 4:
            self.pre = [NSPredicate predicateWithFormat:
                   @"(category like %@)",@"*后期处理*"];
            break;
        case 5:
            self.pre = [NSPredicate predicateWithFormat:
                   @"(category like %@)",@"*器材资讯*"];
            break;
        default:
            self.pre = nil;
            break;
    }
    cdrequest = [[NSFetchRequest alloc]init];

    [cdrequest setPredicate:self.pre];
    [cdrequest setEntity:entity];
    self.blogs = [context executeFetchRequest:cdrequest error:&error];
    [cdrequest release];
    blogcount = [self.blogs count];
    [self.blogstable reloadData];}

- (void)viewDidLoad
{
                                            
    [[UIDevice currentDevice] systemVersion];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9) {
        
        //iOS 5
        UIImage *toolBarIMG = [UIImage imageNamed: @"Navtop.png"];  
        
        if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) { 
            [self.navigationController.navigationBar setBackgroundImage:toolBarIMG forBarMetrics:UIBarMetricsDefault]; 
            [self.topBar setBackgroundImage:toolBarIMG forToolbarPosition:0 barMetrics:0];
        }
        
    } 
    self.navigationItem.title = @"Imgii视觉杂志";

    
    appdelegate = [[UIApplication sharedApplication]delegate];
    context = [appdelegate managedObjectContext];
    entity =[NSEntityDescription entityForName:@"Blog" inManagedObjectContext:context];
    cdrequest = [[NSFetchRequest alloc]init];
    [cdrequest setPredicate:self.pre];
    [cdrequest setEntity:entity];
    self.blogs = [context executeFetchRequest:cdrequest error:&error];
    blogcount = [self.blogs count];
    currentCount = blogcount;
    [cdrequest release];
    page = (currentCount/10)+1;
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    self.controllers = nil;
    [super viewDidUnload];

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark-
#pragma mark Table View DataSource Methods

-(IBAction)refreshPosts:(id)sender
{
    self.operationQueue = [[NSOperationQueue alloc] init];
    NSString *postUrl = [[NSString alloc]initWithFormat:@"http://www.imgii.com/?wpapi=get_posts&content=1&count=10&comment=1&page=%d",page];    
    //NSLog(@"blogs geting %d",currentCount);
    NSURL *url = [NSURL URLWithString:postUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray *posts = [JSON valueForKeyPath:@"posts"];
        for (NSInteger i =0; i < [posts count]; i++) {
            cdrequest = [[NSFetchRequest alloc]init];
            entity = [NSEntityDescription entityForName:@"Blog" inManagedObjectContext:context];
            [cdrequest setEntity:entity];
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"(blogid = %@)",[[posts objectAtIndex:i] valueForKey:@"id"]];
            [cdrequest setPredicate:pred];
            
            NSManagedObject *blogContext = nil;
            NSArray *bloglist = [context executeFetchRequest:cdrequest error:&error];
            if (bloglist == nil) {
                NSLog(@"error because of %@",[error localizedDescription]);
            }
            NSLog(@"blogs count = %d",[bloglist count]);
            if([bloglist count] >0)
            {
                blogContext = [bloglist objectAtIndex:0];
                
            }else
            {
                blogContext = [NSEntityDescription insertNewObjectForEntityForName:@"Blog" inManagedObjectContext:context];
                currentCount++;
            }         
            
            [blogContext setValue:[[posts objectAtIndex:i] valueForKey:@"id"] forKey:@"blogid"];
            [blogContext setValue:[[posts objectAtIndex:i] valueForKey:@"status"] forKey:@"status"];
            [blogContext setValue:[[posts objectAtIndex:i] valueForKey:@"title"] forKey:@"title"];
            [blogContext setValue:[[posts objectAtIndex:i] valueForKey:@"date"] forKey:@"dateCreated"];
            [blogContext setValue:[[posts objectAtIndex:i] valueForKey:@"comment_count"] forKey:@"commentcount"];
            [blogContext setValue:NO forKey:@"collect"];  
            [blogContext setValue:NO forKey:@"alread"];         
            NSArray *xx = [[posts objectAtIndex:i] valueForKeyPath:@"tag.name"];
            
            if ([xx count]>0) {
                NSString *temptags = [[NSString alloc] initWithFormat:[xx componentsJoinedByString:@", "]];
                [blogContext setValue:temptags forKey:@"tag"];
                [temptags release];
            }
            

            xx = [[posts objectAtIndex:i]valueForKeyPath:@"category.name"];
            if ([xx count]>0) {
                NSString *tempCategorie = [[NSString alloc] initWithFormat:[xx componentsJoinedByString:@", "]];
                [blogContext setValue:tempCategorie forKey:@"category"];
                [tempCategorie release];
            }

           
            xx = [[posts objectAtIndex:i]valueForKeyPath:@"comments"];
            if ([xx count]>0) {

                NSFetchRequest *comrequest = [[NSFetchRequest alloc]init];
                NSEntityDescription *comentity = [NSEntityDescription entityForName:@"Comment" inManagedObjectContext:context];
                [comrequest setEntity:comentity];
                for (NSInteger j=0; j< [xx count]; j++) {
                    pred = [NSPredicate predicateWithFormat:@"(commentid = %@)",[[xx objectAtIndex:j] valueForKey:@"id"]];
                    [comrequest setPredicate:pred];
                    
                    NSManagedObject *CommContext = nil;
                    NSArray *Commlist = [context executeFetchRequest:comrequest error:&error];
                    if (Commlist == nil) {
                        NSLog(@"error because of %@",[error localizedDescription]);
                    }
                    NSLog(@"blogs count = %d",[Commlist count]);
                    if([Commlist count] >0)
                    {
                        CommContext = [Commlist objectAtIndex:0];
                        
                    }else
                    {
                        CommContext = [NSEntityDescription insertNewObjectForEntityForName:@"Comment" inManagedObjectContext:context];
                    }
                    [CommContext setValue:[[xx objectAtIndex:j] valueForKey:@"id"] forKey:@"commentid"];
                    [CommContext setValue:[[posts objectAtIndex:i] valueForKey:@"id"] forKey:@"blogid"];
                    [CommContext setValue:[[xx objectAtIndex:j] valueForKey:@"content"] forKey:@"content"];
                    [CommContext setValue:[[xx objectAtIndex:j] valueForKey:@"date"] forKey:@"date"];
                    [CommContext setValue:[[xx objectAtIndex:j] valueForKey:@"author"] forKey:@"author"];
                    
                    //NSLog(@"test comment %@",[[xx objectAtIndex:j] valueForKey:@"content"]);
                }
   
                [comrequest release];
            }
            NSArray *tempContent = [self addUrl:[[posts objectAtIndex:i] valueForKey:@"content"]];
            
            [blogContext setValue:[tempContent objectAtIndex:0] forKey:@"context"];
            [blogContext setValue:[tempContent objectAtIndex:1]  forKey:@"imgurl"];
            [blogContext setValue:[tempContent objectAtIndex:2]  forKey:@"url"];            
            [blogContext setValue:[tempContent objectAtIndex:3]  forKey:@"thumbnail"];

            //NSLog(@"pages: %@", [tempContent objectAtIndex:1]);
            
            
            [cdrequest release];
            
        }
        [context save:&error];
        cdrequest = [[NSFetchRequest alloc]init];
        [cdrequest setEntity:entity];
        [cdrequest setPredicate:self.pre];
        self.blogs = [context executeFetchRequest:cdrequest error:&error];
        [cdrequest release];
        blogcount = [self.blogs count];
        //currentCount = blogcount;
        [self.blogstable reloadData];
        [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
        page = (currentCount/10)+1;
        
    } failure:nil];    
    [self.operationQueue addOperation:operation];
}


- (NSString*)uniquePath{
    // prepare the directory string
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // acquire a list of all files within the directory and loop creating a unique file name
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *existingFiles = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSString *uniquePath;
    do {
        CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
        CFStringRef newUniqueIdString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
        
        uniquePath = [[documentsDirectory stringByAppendingPathComponent:(__bridge NSString *)newUniqueIdString] stringByAppendingPathExtension:@"png"];
        
        CFRelease(newUniqueId);
        CFRelease(newUniqueIdString);
    } while ([existingFiles containsObject:uniquePath]);
    
    return uniquePath;
}



-(NSArray *)addUrl:(NSString *)tcontext{
    NSMutableArray *xcontext = [[NSMutableArray alloc]init];
    NSMutableArray *imgurlArry = [[NSMutableArray alloc]init];
    NSMutableArray *localArray = [[NSMutableArray alloc]init];
    NSString *regexString = @"<img[^>]+alt=\"([^>]+)\"[^>]*>";
    NSArray *splitArray = [tcontext componentsMatchedByRegex:regexString];
    for (NSInteger i = 0; i < [splitArray count]; i++) {
        regexString  = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
        NSArray *tempArry = [[splitArray objectAtIndex:i] componentsMatchedByRegex:regexString];
        [imgurlArry addObject:[tempArry objectAtIndex:0]];
        [localArray addObject:[self uniquePath]];
        NSString *temp = [[NSString alloc]initWithFormat:@"<a href=\"pic:file://%@\">%@</a>",[tempArry objectAtIndex:0],[splitArray objectAtIndex:i]];
        if ([splitArray objectAtIndex:i] != nil && temp !=nil){
            tcontext = [tcontext stringByReplacingOccurrencesOfString:[splitArray objectAtIndex:i] withString:temp];
        }
        [temp release];
    } 
    for (NSInteger i = 0; i < [imgurlArry count]; i ++) {
        if ([imgurlArry objectAtIndex:i] != nil && [localArray objectAtIndex:i] !=nil) {
                    tcontext = [tcontext stringByReplacingOccurrencesOfString:[imgurlArry objectAtIndex:i] withString:[NSString stringWithFormat:@"file://%@",[localArray objectAtIndex:i]]];
        }

    }
    [xcontext addObject:tcontext];
    [xcontext addObject:[imgurlArry componentsJoinedByString:@", "]];
    [xcontext addObject:[localArray componentsJoinedByString:@", "]];
    
    
    if ([localArray count] > 0) {
        [xcontext addObject:[NSString stringWithFormat:@"file://%@",[localArray objectAtIndex:0]]];
    }else
    {
        [xcontext addObject:@""];
    }
    
    NSArray *reContext = [NSArray arrayWithArray:xcontext];
    [xcontext release];
    [imgurlArry release];
    [localArray release];
    return reContext;
}



#pragma mark-
#pragma mark Table View Delegate Methods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.blog = [self.blogs objectAtIndex:[indexPath row]];
    NSLog(@"row is %d",[indexPath row]);
    blogViewController *blogviewController = [[blogViewController alloc]initWithNibName:@"blogViewController" bundle:nil];
    blogviewController.blog = [self.blogs objectAtIndex:[indexPath row]];
    [self.navigationController pushViewController:blogviewController animated:YES];
    [blogviewController release];
}

#pragma mark-
#pragma mark Table View Data Source Methods 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (_refreshHeaderView != nil) {
        [_refreshHeaderView removeFromSuperview];
    }
    
    NSInteger height = [blogstable rowHeight] * blogcount;
    blogstable.contentSize =CGSizeMake(320,height);
    EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, blogstable.contentSize.height, 320, 480)];
    
    view.delegate = self;
    [self.blogstable addSubview:view];
    _refreshHeaderView = view;
    [view release];
    if ([self.blogs count] ==0) {
        return 1;
    }
    return [self.blogs count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleIdent = @"simpleIdent";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleIdent];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleIdent]autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    }
    if ([indexPath row] == blogcount) {
        cell.textLabel.text = @"刷新";

    }else{
        self.blog = [self.blogs objectAtIndex:[indexPath row]];
        cell.textLabel.text = blog.title;
        cell.detailTextLabel.text = blog.context;
    } 
    return cell;
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
    [self refreshPosts:0];
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.blogstable];
	
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

@end
